//
//  MYGPatientDetailViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/18.
//

import UIKit
import JXSegmentedView

class MYGPatientDetailViewController: MYGBaseController {
    var caseClampListTitleArr:[String] = []
    var caseClampListArr:[[MYGCaseClasmListModel]] = []
//    var zhenduanStr:String = ""
    var selectedrow = 0
    var selectedsection = 0

    var selectCaseModel = MYGCaseClasmListModel()
    var patientModel:MYGMyPatientModel = MYGMyPatientModel(){
        didSet{
            headerImageV.sd_setImage(with: URL(string: patientModel.patient.avatar))
            nameLabel.text = patientModel.patient.name
            ageLabel.text = "\(patientModel.patient.birthday) \(patientModel.patient.gender == 1 ? "男":"女")"
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "患者管理"
        navigationBarShow()
        initUI()
        getDatasource()
    }
    @objc private func chatAction(){
        let phone = "\(patientModel.patient.phone)2"
        let vc = MYGChatController(sessionId: patientModel.patient.im_user_id,mobile:phone,title: patientModel.patient.name)
        self.navigationController?.pushViewController(vc)
    }
    @objc private func pushToSelect(){
        let vc = MYGDoctorSelectViewController()
        vc.caseModel = selectCaseModel
        self.navigationController?.pushViewController(vc)
    }
    func getList(clampId:Int){
        MYGLoading.show()
        MMYGNetwork<MYGCaseFilesApi,MYGCaseListFileModel>.request(target: .getClassClampInfo(id: clampId)) { item in
            MYGLoading.hide()
            guard let model = item else {
                return
            }
//            self.model = model
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    private func getDatasource(){
        MYGNetwork<MYGSurgicalApi, MYGPageModel<MYGCaseClasmListModel>>.request(target: .patientCaseList(params: [
            "patient_id":patientModel.patient_id,
            "key":"",
            "type":"2"])) {[self] item in
                item.list.forEach { mod in
                    let prefixSubStr = mod.outpatient.time.prefix(10)
                    if !caseClampListTitleArr.contains(String(prefixSubStr)){
                        caseClampListTitleArr.append(String(prefixSubStr))
                    }
                }
                caseClampListTitleArr.forEach { str in
                    caseClampListArr.append([])
                }
                if item.list.count > 0{
                    for ind in 0...item.list.count - 1{
                        let mod = item.list[ind]
                        for titleInd in 0...caseClampListTitleArr.count - 1{
                            if mod.outpatient.time.prefix(10) == caseClampListTitleArr[titleInd]{
                                var arr = caseClampListArr[titleInd]
                                arr.append(mod)
                                caseClampListArr[titleInd] = arr
                            }
                        }
                    }
                }
                leftTableView.reloadData()
            } failed: { _, error in
                MMYGHUD.showToast(text: error)
            }
    }
    @objc func detailTableBack(){
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: UIButton())
        detailTableView.isHidden = true
    }
    @objc func shareAction(){
        self.popup.bottomSheet(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = MYGPatientDetailShareView()
            actionSheet.patientId = patientModel.patient_id
            actionSheet.dismissBlock = {
                self.popup.dismissPopup()
            }
            actionSheet.nextBlock = {value in
                self.popup.dismissPopup()
                self.showcaseSelectList(paId: value)
            }
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: screenWidth , height: screenHeight)
            return actionSheet
        }
//        MYGPatientDetailViewController.keyWindow?.addSubview(shareView)
//        shareView.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//        }

    }
    @objc func showcaseSelectList(paId:Int){
        self.popup.bottomSheet(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = MYGCaseFileSelectView()
            actionSheet.patientId = paId
            actionSheet.dismissBlock = {
                self.popup.dismissPopup()
            }
            actionSheet.nextBlock = {value in
                self.selectCaseModel = value
                self.popup.dismissPopup()
                self.pushToSelect()

            }
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: screenWidth , height: screenHeight)
            return actionSheet
        }
    }
    private func initUI(){
        view.addSubviews([headerImageV,nameLabel,ageLabel,chatBtn,shareBtn,bottomLabel,bottomView])
        headerImageV.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(25)
            make.top.equalToSuperview().offset(15)
            make.width.height.equalTo(50)
        }
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(headerImageV.snp.right).offset(11)
            make.top.equalToSuperview().offset(17.5)
            make.height.equalTo(22.5)
        }
        ageLabel.snp.makeConstraints { make in
            make.left.equalTo(headerImageV.snp.right).offset(11)
            make.top.equalTo(nameLabel.snp.bottom).offset(6)
            make.height.equalTo(16.5)
        }
        shareBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-26)
            make.centerY.equalTo(headerImageV)
            make.height.width.equalTo(38)
        }
        chatBtn.snp.makeConstraints { make in
            make.right.equalTo(shareBtn.snp.left).offset(-9)
            make.centerY.equalTo(headerImageV)
            make.height.width.equalTo(38)
        }
        bottomLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(41.5)
            make.top.equalTo(headerImageV.snp.bottom).offset(17)
            make.height.equalTo(22.5)
        }
        bottomView.snp.makeConstraints { make in
            make.centerX.equalTo(bottomLabel)
            make.bottom.equalTo(bottomLabel.snp.bottom).offset(6)
            make.size.equalTo(CGSize(width: 16, height: 3))
        }
        //        view.addSubview(scView)
        //        scView.snp.makeConstraints { make in
        //            make.left.right.bottom.equalToSuperview()
        //            make.width.equalTo(screenWidth*2)
        //            make.top.equalTo(bottomView.snp.bottom)
        //        }
        //        view.layoutIfNeeded()
        //        scView.addSubview(contaneriView)
        //        contaneriView.snp.makeConstraints { make in
        //            make.edges.equalToSuperview()
        //        }
        view.addSubview(leftTableView)
        leftTableView.snp.makeConstraints { make in
            make.left.bottom.equalToSuperview()
            make.top.equalTo(bottomView.snp.bottom)
            make.width.equalTo(screenWidth)
        }
        view.addSubview(detailTableView)
        detailTableView.isHidden = true
        detailTableView.snp.makeConstraints { make in
            make.left.bottom.equalToSuperview()
            make.top.equalTo(bottomView.snp.bottom)
            make.width.equalTo(screenWidth)
        }
        //        view.addSubview(segmentedView)
        //        segmentedView.snp.makeConstraints { make in
        //            make.left.right.equalToSuperview()
        //            make.height.equalTo(SCALEWIDTH(45))
        //            make.top.equalTo(headerImageV.snp.bottom).offset(13)
        //        }
        //        view.addSubview(listContainerView)
        //        listContainerView.snp.makeConstraints { make in
        //            make.left.right.equalToSuperview()
        //            make.bottom.equalToSuperview()
        //            make.top.equalTo(segmentedView.snp.bottom)
        //        }
        //        //关联listContainer
        //        segmentedView.listContainer = listContainerView
    }
    //    lazy var scView:UIScrollView = {
    //        let cont = UIScrollView()
    //        cont.isScrollEnabled = false
    //        return cont
    //    }()
    //    lazy var contaneriView:UIView = {
    //        let cont = UIView()
    //        return cont
    //    }()
    lazy var leftTableView: UITableView = {
        let control = UITableView(frame: CGRectZero, style: .grouped)
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.register(cellWithClass: MYGMedicalBookTableViewCell.self)
        return control
    }()
    lazy var detailTableView: UITableView = {
        let control = UITableView()
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.register(cellWithClass: MYGMedicalBookTableViewCell.self)
        return control
    }()
    private lazy var headerImageV:UIImageView = {
        let cont = UIImageView()
        cont.layerCornerRadius = 25
        cont.contentMode = .scaleAspectFill
        return cont
    }()
    lazy var nameLabel: UILabel = {
        let cont = UILabel()
        cont.text = "乔碧萝"
        cont.font = .medium(16)
        cont.textColor = .rgba(44, 44, 44)
        return cont
    }()
    lazy var ageLabel: UILabel = {
        let cont = UILabel()
        cont.text = "27岁 女"
        cont.font = .regular(12)
        cont.textColor = .rgba(128, 128, 128, 1)
        return cont
    }()
    private lazy var chatBtn:UIButton = {
        let vi = UIButton()
        vi.setImage(UIImage(named: "patientDetail_chat"), for: .normal)
        vi.addTarget(self, action: #selector(chatAction), for: .touchUpInside)
        return vi
    }()
    private lazy var shareBtn:UIButton = {
        let vi = UIButton()
        vi.setImage(UIImage(named: "patientDetail_share"), for: .normal)
        vi.addTarget(self, action: #selector(shareAction), for: .touchUpInside)
        return vi
    }()
    lazy var bottomLabel: UILabel = {
        let cont = UILabel()
        cont.text = "病历本"
        cont.font = .regular(16)
        cont.textColor = .rgba(32, 92, 255, 1)
        return cont
    }()
    lazy var bottomView: UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(32, 92, 255, 1)
        return cont
    }()
    lazy var rightBarButton:UIButton = {
        let cont = UIButton()
        cont.setTitle("返回", for: .normal)
        cont.setTitleColor(.rgba(51, 51, 51), for: .normal)
        cont.addTarget(self, action: #selector(detailTableBack), for: .touchUpInside)
        cont.titleLabel?.font = .medium(15)
        return cont
    }()
    //    private lazy var listContainerView: JXSegmentedListContainerView = {
    //        let vi = JXSegmentedListContainerView(dataSource: self)
    //        return vi
    //    }()
    //    private lazy var segmentedView: JXSegmentedView = {
    //        let segmentedView = JXSegmentedView()
    //        segmentedView.delegate = self
    //        segmentedView.dataSource = dataSource
    //        let indicator = JXSegmentedIndicatorLineView()
    //        indicator.indicatorWidth = SCALEWIDTH(16)
    //        indicator.indicatorHeight = SCALEWIDTH(3)
    //        indicator.indicatorColor = .rgba(32, 92, 255, 1)
    //        segmentedView.indicators = [indicator]
    //        return segmentedView
    //    }()
    //
    //    private lazy var dataSource: JXSegmentedTitleDataSource = {
    //        let dataSource = JXSegmentedTitleDataSource()
    //        dataSource.titles = ["病历本","随访计划","患者计划"]
    //        dataSource.titleNormalFont = .regular(13)
    //        dataSource.titleNormalColor = .rgba(118, 118, 118, 1)
    //        dataSource.titleSelectedFont = .regular(16)
    //        dataSource.titleSelectedColor = .rgba(32, 92, 255, 1)
    //        dataSource.isItemSpacingAverageEnabled = true
    //        return dataSource
    //    }()
//    lazy var shareView:MYGPatientDetailShareView = {
//        let vi = MYGPatientDetailShareView()
//    
//        return vi
//    }()
}
extension MYGPatientDetailViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if tableView == leftTableView {
            return 97.5
        }
        return 97.5
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView == leftTableView {
            return caseClampListTitleArr.count
        }
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == leftTableView {
            let arr = caseClampListArr[section]
            return arr.count
        }
        if caseClampListArr.count > 0 {
            return 5
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView == leftTableView {
            return 50
        }
        return 20
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let vi = UIView()
        vi.layer.masksToBounds = true
        vi.backgroundColor = .white
        if tableView == leftTableView {
            let lineView = UIView()
            vi.addSubview(lineView)
            lineView.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(21.5)
                make.centerY.equalToSuperview()
                make.width.equalTo(3)
                make.height.equalTo(15)
            }
            lineView.addCAGradientLayerColor(colors: [RGBA(r: 73, g: 117, b: 236, a: 1).cgColor,RGBA(r: 151, g: 179, b: 255, a: 1).cgColor], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 1))
            let timeLabel = UILabel()
            timeLabel.text = caseClampListTitleArr[section]
            timeLabel.font = .medium(15)
            timeLabel.textColor = .rgba(34, 34, 34)
            vi.addSubview(timeLabel)
            timeLabel.snp.makeConstraints { make in
                make.left.equalTo(lineView.snp.right).offset(10)
                make.centerY.equalTo(lineView)
                make.height.equalTo(21)
            }
//            let dateLabel = UILabel()
//            dateLabel.text = "今日"
//            dateLabel.font = .regular(12)
//            dateLabel.textColor = .rgba(114, 114, 114)
//            vi.addSubview(dateLabel)
//            dateLabel.snp.makeConstraints { make in
//                make.left.equalTo(timeLabel.snp.right).offset(8)
//                make.centerY.equalTo(lineView)
//                make.height.equalTo(21)
//            }
        }
        
        return vi
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == leftTableView {
            let cell = tableView.dequeueReusableCell(withClass: MYGMedicalBookTableViewCell.self, for: indexPath)
            cell.selectionStyle = .none
            let arr = caseClampListArr[indexPath.section]
            cell.mode = arr[indexPath.row]
            return cell
        }
        let cell = tableView.dequeueReusableCell(withClass: MYGMedicalBookTableViewCell.self, for: indexPath)
        cell.selectionStyle = .none
        cell.moreImage.isHidden = true
//        var model = MYGCaseClasmListModel()
//        model.outpatient.hospital = ["门诊","检验/检查","用药记录","手术","体检"][indexPath.row]
        if caseClampListArr.count > 0 {
            let arr = caseClampListArr[selectedsection]
            let mod = arr[selectedrow]
//            cell.mode = mod
            cell.hospitalLabel.text = ["门诊","检验/检查","用药记录","手术","体检"][indexPath.row]
            switch indexPath.row {
            case 0:
                cell.contentLab.text = "诊断:\(mod.outpatient.info)"
                if mod.outpatient.img.count > 0{
                    cell.imageV.sd_setImage(with: URL(string: mod.outpatient.img[0]))
                }
                break
            case 1:
                cell.contentLab.text = "检查名称:\(mod.inspection.info)"
                if mod.inspection.img.count > 0{
                    cell.imageV.sd_setImage(with: URL(string: mod.inspection.img[0]))
                }
                break
            case 2:
                cell.contentLab.text = "用药名称:\(mod.medication.info)"
                if mod.medication.img.count > 0{
                    cell.imageV.sd_setImage(with: URL(string: mod.medication.img[0]))
                }
                break
            case 3:
                cell.contentLab.text = "手术名称:\(mod.operation.info)"
                if mod.operation.img.count > 0{
                    cell.imageV.sd_setImage(with: URL(string: mod.operation.img[0]))
                }
                break
            case 4:
                cell.contentLab.text = "体检机构:\(mod.examination.info)"
                if mod.examination.img.count > 0{
                    cell.imageV.sd_setImage(with: URL(string: mod.examination.img[0]))
                }
                break
            default:
                break
            }
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == leftTableView {
            detailTableView.isHidden = false
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarButton)
            selectedsection = indexPath.section
            selectedrow = indexPath.row
//            zhenduanStr = "诊断: \(arr[indexPath.row].outpatient.info)"
//            getList(clampId: arr[indexPath.row].id)
            detailTableView.reloadData()
        }
    }
}
//extension MYGPatientDetailViewController: JXSegmentedViewDelegate{
//    //点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，而不关心具体是点击还是滚动选中的情况。
//    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {}
//    // 点击选中的情况才会调用该方法
//    func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) {}
//    // 滚动选中的情况才会调用该方法
//    func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) {}
//    // 正在滚动中的回调
//    func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) {}
//}
//extension MYGPatientDetailViewController:JXSegmentedListContainerViewDataSource{
//    //返回列表的数量
//    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
//        return 3
//    }
//    //返回遵从`JXSegmentedListContainerViewListDelegate`协议的实例
//    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
//        let vc = MYGMedicalBookViewController()
//        return vc
//    }
//
//}
